﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using AteneoLibriBusinessLogic.Entities;

namespace AteneoLibri.Pages
{
    public partial class Registration : System.Web.UI.Page
    {

        protected void Page_PreInit(object sender, EventArgs e)
        {
            if (User.Identity.IsAuthenticated)
            {
                if (User.Identity.Name.Equals(System.Configuration.ConfigurationManager.AppSettings["AdminName"]))
                {
                    Page.MasterPageFile = "~/BackEnd/BackEndMasterPage.Master";
                }
                else
                {
                    Page.MasterPageFile = "~/Account/NewAccountMasterPage.Master";
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            BuildPrivacyCheckBoxContent();
            
            if (!Page.IsPostBack)
            {
                // Caricare le università e bindarle nelle dropdown
                using (wsAteneoLibri.AteneoLibriServiceClient service = new wsAteneoLibri.AteneoLibriServiceClient())
                {
                    List<University> universities = service.getUniversities();

                    ddlUniversity.DataSource = universities;
                    ddlUniversity.DataBind();
                }
            }
        }

        private void BuildPrivacyCheckBoxContent()
        {
            string htmlTextPrivacy = " Accetto i <a href=\"../Privacy/condizioni_utilizzo.pdf\">termini d'uso del servizio</a> e acconsento al trattamento dei miei <a href=\"../Privacy/privacy.pdf\">dati personali</a> per le finalità connesse alla fornitura dello stesso (punto 1 dell'informativa)";
            chkPrivacy.Text = htmlTextPrivacy;
            string htmlTextThirdParty = " Acconsento al trattamento dei miei dati personali per l'invio di informazioni ed offerte commerciali da parte di soggetti terzi ai quali sarà possibile per il Titolare comunicare i dati personali da me forniti (<a href=\"../Privacy/privacy.pdf\">punto 5 dell'informativa</a>)";
            chkThirdPartPrivacy.Text = htmlTextThirdParty;
        }

        protected void ddlUniversity_SelectedIndexChanged(object sender, EventArgs e)
        {
            ResetFacultyDropDown();

            using (wsAteneoLibri.AteneoLibriServiceClient service = new wsAteneoLibri.AteneoLibriServiceClient())
            {
                var universityId = ddlUniversity.SelectedItem.Value;
                if (universityId != "0")
                {
                    List<Faculty> faculties = service.getFacultiesByUniversity(new Guid(universityId));
                    ddlFaculty.DataSource = faculties;
                    ddlFaculty.DataBind();
                }
            }
        }

        private void ResetFacultyDropDown()
        {
            ddlFaculty.Items.Clear();
            ddlFaculty.Items.Add("-- Seleziona --");
            ddlFaculty.Items[0].Selected = true;
            ddlFaculty.AppendDataBoundItems = true;
        }

        protected void btnRegistra_Click(object sender, EventArgs e)
        {
            recaptcha.Validate();
            if (recaptcha.IsValid)
            {                
                using (wsAteneoLibri.AteneoLibriServiceClient service = new wsAteneoLibri.AteneoLibriServiceClient())
                {
                    cvUser.IsValid = !service.CheckExistingRegistration(txtEmail.Text.ToLower().Trim());
                    cvUserName.IsValid = !service.UserNameExist(txtUsername.Text.ToLower().Trim());  // Check if the username already exist!

                    pnlErrorPrivacy.Visible = false;
                    pnlError.Visible = false;

                    if (chkPrivacy.Checked) // chkUsageConditions.Checked && 
                    {
                        if (Page.IsValid)
                        {
                            bool result = false;

                            AteneoLibriBusinessLogic.Entities.User user = new AteneoLibriBusinessLogic.Entities.User();
                            user.IdUser = Guid.NewGuid();
                            user.Email = txtEmail.Text.Trim();
                            user.Username = txtUsername.Text.Trim();
                            user.Name = txtName.Text.Trim();
                            user.Surname = txtSurname.Text.Trim();
                            string hashedPassword = Utility.Utility.hash(txtPassword.Text.Trim());
                            user.Password = hashedPassword;
                            user.RecoveryCode = Utility.Utility.generateRecoveryCode(txtEmail.Text.Trim());
                            user.RegistrationData = DateTime.Now;

                            if (ddlUniversity.SelectedItem.Value != "0")
                            {
                                user.UniversityId = new Guid(ddlUniversity.SelectedItem.Value);
                                if (ddlFaculty.SelectedItem.Value != "0")
                                {
                                    user.FacultyId = new Guid(ddlFaculty.SelectedItem.Value);
                                }
                            }

                            user.ThirdPartPrivacy = chkThirdPartPrivacy.Checked;
                            user.VerifyRegistration = false;
                            user.IsSuspended = false;
                            user.MarketingNewsletter = true;

                            user.IPAddress = Utility.Utility.GetIP();

                            result = service.insertUser(user);

                            if (result)
                            { // registrazione effettuata con successo
                                pnlRegistrationSuccessfullyCompleted.Visible = true;
                                pnlRegistrazione.Visible = false;
                                // Invio email con username e password
                                try
                                {
                                    Utility.Mail.MailSender mailSender = new Utility.Mail.MailSender();
                                    // mailSender.SendMail(user.Email, "Registrazione", Utility.Utility.generateRegistrationBody(user.Email, txtPassword.Text.Trim()), true);
                                    mailSender.SendMail(user.Email, "Completamento registrazione su Ateneolibri.it", Utility.Mail.MailText.createValidationLink(user.IdUser), true);
                                }
                                catch (Exception ex)
                                {
                                    // TODO gestire un log con gli errori
                                }
                            }
                            else
                            { // errore di registrazione
                                pnlError.Visible = true;
                                lblError.Text = "Errore durante la registrazione!";
                                ClearField();
                            }

                        }
                    }
                    else
                    {
                        pnlErrorPrivacy.Visible = true;                        
                    }

                }
            }
            else
            {
                pnlError.Visible = true;
                lblError.Text = recaptcha.ErrorMessage;
            }
        }

        private void ClearField()
        {
            txtEmail.Text = string.Empty;
            txtUsername.Text = string.Empty;
            txtPassword.Text = string.Empty;
            txtConfirmPsw.Text = string.Empty;
        }

        protected void btnAnnulla_Click(object sender, EventArgs e)
        {
            ClearField();
            Response.Redirect("~/Default.aspx");
        }

    }
}